﻿using System.Configuration;

namespace Server
{
    class Config
    {
        //获取Configuration对象
        static Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        public static string ReadKey(string KeyName)  //根据Key值取得Value
        {
            string KeyValue = config.AppSettings.Settings[KeyName].Value;
            return KeyValue;
        }

        public static void SaveKey(string KeyName, string KeyValue)  //保存Key值
        {
            config.AppSettings.Settings[KeyName].Value = KeyValue;
            SaveConfig();
        }

        public static void AddKey(string KeyName, string KeyValue)  //增加<add>元素
        {
            config.AppSettings.Settings.Add(KeyName, KeyValue);
            SaveConfig();
        }

        public static void RemoveKey(string KeyName)  //删除Key
        {
            config.AppSettings.Settings.Remove(KeyName);
            SaveConfig();
        }

        static void SaveConfig()
        {
            //一定要记得保存，写不带参数的config.Save()也可以
            config.Save(ConfigurationSaveMode.Modified);
            //刷新，否则程序读取的还是之前的值（可能已装入内存）
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
